import BaseEntity from "../form-render/form-item/components/BaseEntity";
import { computed, ref } from "vue";
import type { Reactive, Ref } from "vue";
import SpaceLayoutEntity from "../form-render/form-item/components/SpaceLayout/entity/SpaceLayoutEntity";
import { assignInWith, cloneDeep } from "lodash";
import { entityType } from "../form-render/form-item/components";
import RouteNode from "../layout/right/form-setting/form-linkage-rules/class/RouteNode";
import RuleNode from "../layout/right/form-setting/form-linkage-rules/class/RuleNode";
import EventActionEntity from "../layout/right/form-setting/form-linkage-rules/actions/class/EventActionEntity";
import useFormRule from "../layout/right/form-setting/form-linkage-rules/hooks/useFormRule";



type _RenderConfigType={
  model:'edit'|'preview'
}

type resultType = { 
  renderConfig:Ref<_RenderConfigType>,
  FormConfig:Ref<Object>,
  FormEntitys: Ref<Array<BaseEntity | SpaceLayoutEntity>>, 
  FormRuleActions: Ref<Array<FormRuleActionsType>>,
  curSelectFormComponent: Ref<BaseEntity | undefined>,
  aliveFormDataInLocalStorage: () => void,
  saveFormDataInLocalStorage: () => void,
  selectFormComponent: (formComponent: BaseEntity) => void, 
  removeEntity: (entity: BaseEntity) => void,
  clearFormEntitys:()=>void ,
  setFormConfig:(config:Object)=>void,
  setRenderConfig:<T extends keyof _RenderConfigType>(configKey: T, val: _RenderConfigType[T]) => void;
}


//中间区域表单渲染器得配置
let _RenderConfig:Ref<_RenderConfigType>=ref({
  model:'edit',//'edit'|'preview'  //默认为可编辑模式，可编辑模式下可进行拖拽，且部分组件样式会和预览模式存在区别
})


//中间拖拽区域得表单配置
let FormConfig=ref({
  autoLabelWidth: true,
  layout:'vertical'
})
let curSelectFormComponent: Ref<BaseEntity | undefined> = ref()
let historySelectFormComponent: Ref<Array<BaseEntity | undefined>> = ref([])
let FormEntitys: Ref<Array<BaseEntity | SpaceLayoutEntity>> = ref([])//中间区域表单渲染器得表单实例数组

//表单联动规则列表
export type FormRuleActionsType={
  AllNode:RouteNode | undefined,
  NodeEventActionList:Array<EventActionEntity>
}
let FormRuleActions: Ref<Array<FormRuleActionsType>> = ref([])




export default function useForm(): resultType {

  let renderConfig=computed(()=>{
    return _RenderConfig.value
  })

  function setRenderConfig<T extends keyof _RenderConfigType>(configKey:T,val:_RenderConfigType[T]){
    if(configKey=='model'&&val=='preview'){
      curSelectFormComponent.value=undefined
    }
    _RenderConfig.value[configKey]=val
  }

  return {
    renderConfig,
    FormConfig:FormConfig,
    FormEntitys: FormEntitys,
    FormRuleActions:FormRuleActions,
    curSelectFormComponent,
    saveFormDataInLocalStorage() {
      let formData={
        FormEntitys:cloneDeep(FormEntitys.value),
        FormRuleActions:cloneDeep(FormRuleActions.value)
      }
      localStorage.setItem('FormData', JSON.stringify(formData))
    },

    //将保存在本地的表单数据恢复响应式
    aliveFormDataInLocalStorage() {
      let {aliveAllRuleAction}=useFormRule()
      let formData = JSON.parse(localStorage.getItem('FormData') ?? '')
      if (formData) {
        FormEntitys.value = formData.FormEntitys
        let flatFormEntitys=ref([])
        flatFormEntitysFn(FormEntitys.value,flatFormEntitys)
        FormRuleActions.value = formData.FormRuleActions
        FormRuleActions.value.forEach((ruleAction) => {
          aliveAllRuleAction(ruleAction, flatFormEntitys.value)
        })
      }
    },

    selectFormComponent(formComponent: BaseEntity) {
      if (_RenderConfig.value.model == 'preview') {
        return
    }
      curSelectFormComponent.value = formComponent
      let historyIndex = historySelectFormComponent.value.findIndex((item) => (item as BaseEntity).config.field === formComponent.config.field)
      if (historyIndex == -1) {
        historySelectFormComponent.value.push(formComponent)
      }
      changeStyle(formComponent)
    },
    removeEntity(entity: BaseEntity) {

      FormEntitys?.value.forEach((item: BaseEntity | SpaceLayoutEntity) => {
        if (item.config.field == entity.config.field) {
          FormEntitys.value.splice(FormEntitys.value.indexOf(item), 1)
        }
        if (item.type === 'space-layout') {
          delChidrenEntity(entity, item as SpaceLayoutEntity)
        } 
         
      })
      curSelectFormComponent.value = undefined
    },
    clearFormEntitys(){
      FormEntitys.value.splice(0,FormEntitys.value.length)
    },
    setFormConfig(config:Object){
      FormConfig.value=assignInWith(FormConfig.value,config)
    },
    setRenderConfig
    
  }
}



//将当前选中得组件样式设置为选中样式
function changeStyle(entity) {
  if(_RenderConfig.value.model=='preview') return
  historySelectFormComponent.value.forEach(entity => {
    (entity as BaseEntity).config.class.findIndex((item: string) => item === 'select-active') > -1 && entity!.config.class.splice(entity!.config.class.findIndex((item: string) => item === 'select-active'), 1)
  })
  entity.config.class.push('select-active')
}

function delChidrenEntity(entity: BaseEntity, parentEntity: SpaceLayoutEntity) {
  parentEntity.config.childrenEntitys.forEach((draggableEnitys: Array<BaseEntity | SpaceLayoutEntity | null>) => {

    if (entity.config.field === draggableEnitys[0]?.config.field) {
      draggableEnitys[0] = null
    }
    if (draggableEnitys[0]?.type === 'space-layout') {
      delChidrenEntity(entity, draggableEnitys[0] as SpaceLayoutEntity)
    }

  })
}

//递归扁平化表单实例数组
export function flatFormEntitysFn(FormEntitys:Array<BaseEntity|SpaceLayoutEntity>,flatFormEntitys:Ref<Array<BaseEntity>>){
  for(let i=0;i<FormEntitys.length;i++){
    let entity=FormEntitys[i]
    if(entity==null) continue
    if(entity.type!=entityType.spaceLayout){
      flatFormEntitys.value.push(entity)
    }else{
      for(let j=0;j<entity.config.childrenEntitys.length;j++){
        flatFormEntitysFn(entity.config.childrenEntitys[j],flatFormEntitys)
      }
    }
  }
}